﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml;
using Autodesk.Revit.DB;
using YArchitech.LIB;
using YArchitech.Revit;

namespace YArchitech.HVAC
{
	internal static class SavePipe
	{
		internal static string FileName { get; set; }  //; = "HeatingCalcPipeInfo"

		internal static string FilePath { get; set; }

		internal static void Add(PipeLine pl)
		{
			SavePipe.dataFile = SavePipe.GetFileName();
			Log.Info(new string[]
			{
				SavePipe.dataFile
			});
			if (!File.Exists(SavePipe.dataFile))
			{
				SavePipe.CreateFile();
			}
			if (!SavePipe.AddToXmlNode(SavePipe.PipeFormat(pl)))
			{
				Log.Info(new string[]
				{
					"节点添加异常！！！"
				});
			}
		}

		private static string GetFileName()
		{
			string empty = string.Empty;
			string empty2 = string.Empty;
			return Path.Combine((SavePipe.FilePath == null || SavePipe.FilePath == "") ? Product.WorkingLocation : SavePipe.FilePath, string.Format("{2}_InFile_{0}_{1}.xml", SavePipe.FileName, DateTime.Now.ToString("yyyy-MM-dd_HHmm"), "散热器水力计算"));
		}

		private static bool CreateFile()
		{
			List<LinkedDocument> list = RevitUtility.LinkedDocuments.ToList<LinkedDocument>();
			List<string> list2 = new List<string>();
			foreach (LinkedDocument linkedDocument in list)
			{
				string text = linkedDocument.Document.Title;
				if (text.LastIndexOf(".rvt") > 0)
				{
					text = text.Substring(0, text.LastIndexOf(".rvt"));
				}
				list2.Add(text);
			}
			return HYUpdateLinkedDocXML.AddRootAndFileListNodes(SavePipe.dataFile, MajorSystemType.UndefinedSystem, list2);
		}

		private static bool AddToXmlNode(HYUpdateElementInfo elemInfo)
		{
			return HYUpdateLinkedDocXML.AddElementListToXML(SavePipe.dataFile, elemInfo.DocumentTitle, new List<HYUpdateElementInfo>
			{
				elemInfo
			});
		}

		private static XmlNode SelectXmlNode(ref XmlDocument xmlDoc, ref XmlNode parentNode, string nodeName)
		{
			return parentNode.SelectSingleNode(nodeName) ?? SavePipe.CreateXmlNode(ref xmlDoc, ref parentNode, nodeName);
		}

		private static XmlNode CreateXmlNode(ref XmlDocument xmlDoc, ref XmlNode parentNode, string nodeName)
		{
			XmlElement xmlElement = xmlDoc.CreateElement(nodeName);
			parentNode.AppendChild(xmlElement);
			return xmlElement;
		}

		private static HYUpdateElementInfo PipeFormat(PipeLine pl)
		{
			HYUpdateElementInfo hyupdateElementInfo = new HYUpdateElementInfo();
			hyupdateElementInfo.DocumentTitle = pl.Element.Document.Title.Substring(0, pl.Element.Document.Title.LastIndexOf(".rvt"));
			hyupdateElementInfo.ElementID = pl.Id.IntegerValue;
			Category category = pl.Element.Document.Settings.Categories.get_Item(BuiltInCategory.OST_PipeCurves);
			hyupdateElementInfo.CategoryName = category.Name;
			hyupdateElementInfo.FLow = pl.Flow;
			hyupdateElementInfo.Velocity = pl.Velocity;
			hyupdateElementInfo.PipeDN = pl.DN;
			return hyupdateElementInfo;
		}

		private static string dataFile = string.Empty;
	}
}
